package com.escom.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.escom.R;
import com.escom.service.SincronizarWebService;
import com.escom.utils.Constantes;


public class SincronizarFragment extends Fragment {


    private View viewActivity;
    private Context context;
    private Handler handler;
    private SharedPreferences sharedpreferences;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        viewActivity = inflater.inflate(R.layout.fragment_sincronizar, container, false);
        context = getActivity().getApplicationContext();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                int codeResponse = msg.getData().getInt("message");
                switch (codeResponse) {
                    case Constantes.EXITO:
                        Toast.makeText(getActivity().getApplicationContext(), "Exito", Toast.LENGTH_SHORT).show();
                        break;
                    case Constantes.ERROR_COMUNICACION:
                        Toast.makeText(getActivity().getApplicationContext(), "Error al actulizar. Intentelo de nuevo", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
        setListenerButtons();
        return viewActivity;
    }

    private void setListenerButtons() {
        Button btnSync = (Button) viewActivity.findViewById(R.id.btnSincronizar);
        btnSync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Log.d("Logger SincronizarFragment", "Boton presionado");
                sharedpreferences = getActivity().getSharedPreferences(Constantes.MY_PREFERENCES, Context.MODE_PRIVATE);
                String idMedico = sharedpreferences.getString(Constantes.ID_MEDICO_KEY,null);
                //Log.d(Constantes.LOG_ID, "ID MEdico : " + idMedico);
                SincronizarWebService sincronizarWebService = new SincronizarWebService();
                sincronizarWebService.setHandler(handler);
                sincronizarWebService.setContext(context);
                sincronizarWebService.setIdMedico(idMedico);
                Thread tareaPaciente = new Thread(sincronizarWebService);
                tareaPaciente.start();
            }
        });
    }

}
